/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011      Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
 
http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 ****************************************************************************/
package org.cocos2dx.cpp;

import java.io.BufferedReader;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URI;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import net.sourceforge.simcpux.Constants;
import net.sourceforge.simcpux.MD5Util;
import net.sourceforge.simcpux.Util;

import org.cocos2dx.cpp.ShakeDetector.OnShakeListener;
import org.cocos2dx.lib.Cocos2dxActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import zxing.android.scanner.CaptureActivity;
import android.Manifest;
import android.R.bool;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences.Editor;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.provider.Settings;
import android.provider.Settings.Secure;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.migame.CompilationConfig;
import com.migame.buyu.R;
import com.migame.permission.PermissionsUtil;
import com.migame.permission.PermissionsUtil.IPermissionsCallback;
import com.migame.sdk.DevicesUtil;
import com.migame.sdk.GameSDK;
import com.migame.sdk.MiitHelper;
import com.mrwujay.cascade.activity.RegionActivity;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import android.os.Handler.Callback;
import android.os.Bundle;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("NewApi")
public class AppActivity extends Cocos2dxActivity implements
		IPermissionsCallback {

	public enum PayResult {
		success, fail, cancle, error
	}

	private static final int REQUEST_CODE_GETIMAGE_BYSDCARD = 0; // 从sd卡得到图像的请求码
	private static final int REQUEST_CODE_GETIMAGE_BYCAMERA = 1; // 从相机得到图像的请求码
	private static final int REQUEST_CODE_CLIPIMAGE_BYSDCARD = 4; // 从sd卡裁剪返回的邀请码
	private static final int REQUEST_CODE_CLIPIMAGE_BYCAMERA = 5; // 从相机裁剪返回的请求码
	private static final int REQUEST_CODE_SCANNIN_GREQUEST = 6; // 扫描二维码
	private static final int REQUEST_CODE_RIGIONALISM = 8; // 选择行政区域
	private static final int REQUEST_CODE_DOWNLOAD_APK_INDEX_Key = 10;
	private static HashMap<Integer, String> apkMap_Info = new HashMap<Integer, String>();
	private static boolean isDownloadApkEnd = false;
	public static ProgressDialog dialogTips = null;
	public static AppActivity nAppActivity = null;
	public static String TAG = "AppActivity";
	
	public static boolean IsPing = true;
	public static String ServerUrl;

	private ClipboardManager mClipboard = null;
	ShakeDetector mShaker;
	public static String sta = null;
	public static int selectImageIndex = 0;
	public static int delSelectImage = 0;
	public static int maxSelectImage = 0;
	public static int shareType = 0;
	public static Uri uritempFile = null;
	FrameLayout m_webLayout;
	WebView m_webView = null;
	ImageView m_imageView;
	LinearLayout topLayout;
	Button backButton;

	// 安卓6.0 动态权限
	private static final int MY_PERMISSIONS_REQUEST_CAMERA = 0; // 相机相册
	private static final int MY_PERMISSIONS_REQUEST_START = 1; // 启动游戏
	static PermissionsUtil permissionsUtil;

	// public static final Bitmap[] saveBitMap={null,null,null,null,null};
	// add lcf
	public static int ltask = 0;
	public static int ltask2 = 0;

	public static int powerlevel = 0;
	public static int powerstate = 0;

	// 爱玩项目所有功能
	static SharedPreferences sharedPreferences;
	// 安装应用监听广播
	InstallReceiver installReceiver;

	public AppActivity() {
		nAppActivity = this;
	}

	public static AppActivity getInstance() {// 返回实例
		return nAppActivity;
	}

	public static void saveLog(String str) {
		File file = new File(Environment.getExternalStorageDirectory()
				.getPath() + "/" + nAppActivity.getPackageName() + "_log.txt");
		try {
			FileWriter filerWriter = new FileWriter(file, true);// 后面这个参数代表是不是要接上文件中原来的数据，不进行覆盖
			BufferedWriter bufWriter = new BufferedWriter(filerWriter);

			Date currentTime = new Date();
			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			String dateString = formatter.format(currentTime);

			bufWriter.write(dateString + " : " + str);
			bufWriter.newLine();
			bufWriter.close();
			filerWriter.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// new AlertDialog.Builder(nAppActivity)
		// .setTitle("警告" )
		// .setMessage(str)
		// .setPositiveButton("确定" , null )
		// .setCancelable(true)
		// .show();
	}

	/**
	 * 隐藏虚拟按键，并且全屏
	 */
	// protected void hideBottomUIMenu(){}
	protected void hideBottomUIMenu() {
		// 隐藏虚拟按键，并且全屏
		if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower
																		// api
			View v = this.getWindow().getDecorView();
			v.setSystemUiVisibility(View.GONE);
		} else if (Build.VERSION.SDK_INT >= 19) {
			// for new api versions.
			View decorView = getWindow().getDecorView();
			// int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
			// | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
			// | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
			// | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
			// | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
			// | View.SYSTEM_UI_FLAG_IMMERSIVE
			// | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;

			int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
					| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
					| View.SYSTEM_UI_FLAG_FULLSCREEN;

			decorView.setSystemUiVisibility(uiOptions);
			// 透明状态栏
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		}
	}

	public static class InstallReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// 接收安装广播
			if (intent.getAction()
					.equals("android.intent.action.PACKAGE_ADDED")) {
				String packageName = intent.getDataString();
				packageName = packageName.substring(8);
				SharedPreferences sharedPreferences = nAppActivity
						.getSharedPreferences("path", Activity.MODE_PRIVATE);
				String savedPackageName = sharedPreferences.getString(
						"OtherPackageName", "");
				if (packageName.equalsIgnoreCase(savedPackageName)) {
					nAppActivity.finish();
				}

			}
			// 接收卸载广播
			if (intent.getAction().equals(
					"android.intent.action.PACKAGE_REMOVED")) {
				String packageName = intent.getDataString();
				// System.out.println("卸载了:" + packageName + "包名的程序");

			}
		}
	}

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		File file = new File(Environment.getExternalStorageDirectory()
				.getPath() + "/" + nAppActivity.getPackageName() + "_log.txt");
		if (file.isFile() && file.exists())
			file.delete();

		sharedPreferences = getSharedPreferences("path", 0);

		saveLog("==========================start=======================");
		hideBottomUIMenu();
		super.onCreate(savedInstanceState);

		saveLog("==========================GameSDK=======================");
		setSDKType(CompilationConfig._compilation_sdktype);
		GameSDK.init(this);
		Log.d("GameSDK", "TestinAgent.init");

		// 防止屏幕休眠
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		saveLog("==========================FrameLayout=======================");
		// 初始化一个空的布局
		m_webLayout = new FrameLayout(this);
		addContentView(m_webLayout, new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));

		// 启动游戏 权限
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			permissionsUtil = PermissionsUtil
					.with(this)
					.requestCode(MY_PERMISSIONS_REQUEST_START)
					.isDebug(true)
					// 开启log
					.permissions(
							PermissionsUtil.Permission.Phone.READ_PHONE_STATE,
							PermissionsUtil.Permission.Storage.WRITE_EXTERNAL_STORAGE,
							PermissionsUtil.Permission.Storage.READ_EXTERNAL_STORAGE)
					.request();
		}

		saveLog("==========================PushAgent=======================");

		installReceiver = new InstallReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("android.intent.action.PACKAGE_ADDED");
		intentFilter.addAction("android.intent.action.PACKAGE_REMOVED");
		this.registerReceiver(installReceiver, intentFilter);
		saveLog("==========================onCreate end=======================");
		
		saveLog("==========================init oaid===========================");
		new MiitHelper().getDeviceIds(this, new MiitHelper.AppIdsUpdater() {
            @Override
            public void OnIdsAvailed(boolean isSupport, String oaid) {
                Log.e(TAG, "support: " + isSupport + " OnIdsAvailed: " + oaid);

                updateOAID(isSupport, oaid);
            }

			
        });
		
		saveLog("==========================init oaid end========================");
		
		mClipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
		mShaker = new ShakeDetector(this);
		mShaker.registerOnShakeListener(new OnShakeListener() {
			@Override
			public void onShake() {
				// TODO Auto-generated method stub
				Log.d("shake2", "shake2: " + "shake2");
			}
		});
		mShaker.start();
	}


	private void updateOAID(boolean isSupport, String oaid) {
		// TODO Auto-generated method stub
		final String configInfo = "support->" + isSupport + "\nMSA_OAID->" + oaid;
		DevicesUtil.isSupportOaid = isSupport;
		DevicesUtil._oaid = oaid;
	}
	
	// 获取手机的坐标和电池信息并发送服务记录
	public static String GetRecordByPhone() {
		float[] poses = AppActivity.nAppActivity.mShaker.getposes();
		JSONObject jo = new JSONObject();
		try {
			jo.put("x", poses[0]);
			jo.put("y", poses[1]);
			jo.put("z", poses[2]);
			jo.put("powerlev", powerlevel);
			jo.put("powerstate", powerstate); // 登录调用
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return jo.toString();
	}

	public void onInitResult(int arg0) {
	}

	public static String getClipText() {
		return nAppActivity.pasteToResult();// pasteText(nAppActivity);
	}

	private String pasteToResult() {
		// Gets a handle to the clipboard service.
		if (null == mClipboard) {
			mClipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
		}

		String resultString = "";
		// 检查剪贴板是否有内容
		if (!mClipboard.hasPrimaryClip()) {
			ToShowToast("empty()");
		} else {
			ClipData clipData = mClipboard.getPrimaryClip();
			int count = clipData.getItemCount();

			for (int i = 0; i < count; ++i) {

				ClipData.Item item = clipData.getItemAt(i);
				CharSequence str = item.coerceToText(nAppActivity);
				Log.i("mengdd", "item : " + i + ": " + str);

				resultString += str;
			}

		}
		return resultString;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		hideBottomUIMenu();
		super.onResume();
		if (isDownloadApkEnd == false) {
			gameComesToForeground();
		} else {
			isDownloadApkEnd = true;
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	public void onRequestPermissionsResult(int requestCode,
			String[] permissions, int[] grantResults) {
		// TODO Auto-generated method stub
		permissionsUtil.onRequestPermissionsResult(requestCode, permissions,
				grantResults);
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
	}

	@Override
	public void onPermissionsGranted(int requestCode, String... permission) {
		// TODO Auto-generated method stub
		// 权限获取回调
		switch (requestCode) {
		case MY_PERMISSIONS_REQUEST_CAMERA: // 打开相机相册
			ChooseImageDialog();
			break;
		case MY_PERMISSIONS_REQUEST_START: // 启动游戏

			break;

		default:
			break;
		}
	}

	@Override
	public void onPermissionsDenied(int requestCode, String... permission) {
		// TODO Auto-generated method stub
		// 权限被拒绝回调
		switch (requestCode) {
		case MY_PERMISSIONS_REQUEST_CAMERA:// 打开相机相册

			break;
		case MY_PERMISSIONS_REQUEST_START:// 启动游戏
			nAppActivity.finish();
			System.exit(0);
			break;

		default:
			break;
		}
	}

	// ======================================消息传递===========================================
	private static final int HANDLER_HINT_MSG = 1;
	private static final int HANDLER_IMAGE_CHOOSE = 2;
	private static final int HANDLER_DOWNLOAD_APK = 3;
	private static final int HANDLER_SHOWVERSION = 4;
	public static final int HANDLER_SHOWDIALOG = 5;
	public static final int HANDLER_CANCELDIALOG = 6;
	public static final int HANDLER_WECHATPAY = 7;
	public static final int HANDLER_OPENWEBVIEW = 8;
	public static final int HANDLER_ZHIYIFU = 9;// 指易付
	public static final int HANDLER_DOWNLOAD_APK_WITH_NAME = 10;
	public static final int HANDLER_INSTALL_APK = 11;
	public static final int HANDLER_YINLIAN = 12;
	public static final int HANDLER_SHARE = 13;
	public static final int HANDLER_WXLogin = 15;
	public static final int HANDLER_CHOOSEIMAGE = 16;
	public static final int HANDLER_COMPRESS = 17;
	public static final int HANDLER_DELIMAGE = 18;
	public static final int HANDLER_SHAREIMAGE = 19;

	private void HintMsg(String msg) {
		Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
	}

	private void WXLogin() {
		Log.d("PHDH", "Weixin login");
		IWXAPI api = WXAPIFactory.createWXAPI(nAppActivity, Constants.APP_ID);
		SendAuth.Req req = new SendAuth.Req();
		sta = (int) (1 + Math.random() * (10000 - 1 + 1)) + "wx";
		req.scope = "snsapi_userinfo";
		req.state = sta;
		api.sendReq(req);
	}

	private void ShareFriend(String msg) {
		JSONObject jo = null;
		JSONArray ja = null;
		try {
			jo = new JSONObject(msg);
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		try {
			WXWebpageObject webpage = new WXWebpageObject();
			webpage.webpageUrl = jo.getString("url");
			WXMediaMessage msg1 = new WXMediaMessage(webpage);

			msg1.title = jo.getString("title");
			msg1.description = jo.getString("des");
			String dir = Environment.getExternalStorageDirectory()
					.getAbsolutePath() + File.separator + "InviteScreen";
			File f = new File(dir, "invite_thumb.png");
			Bitmap thumb = BitmapFactory.decodeFile(f.getAbsolutePath());
			msg1.setThumbImage(thumb);
			SendMessageToWX.Req req1 = new SendMessageToWX.Req();
			// req.transaction = String.valueOf(System.currentTimeMillis());
			req1.message = msg1;
			req1.scene = jo.getInt("type");
			req1.transaction = jo.getString("tasklist");
			IWXAPI api = WXAPIFactory.createWXAPI(nAppActivity,
					Constants.APP_ID);
			api.sendReq(req1);
		} catch (Exception e) {
			ToShowToast(getErrorInfoFromException(e));
		}
	}

	public static Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HANDLER_HINT_MSG:
				String hintmsg = (String) msg.obj;
				nAppActivity.HintMsg(hintmsg);
				break;

			case HANDLER_IMAGE_CHOOSE:
				// 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
					permissionsUtil = PermissionsUtil
							.with(nAppActivity)
							.requestCode(MY_PERMISSIONS_REQUEST_CAMERA)
							.isDebug(true)
							// 开启log
							.permissions(
									PermissionsUtil.Permission.Camera.CAMERA)
							.request();
				} else {
					ChooseImageDialog();
				}
				break;
			case HANDLER_CHOOSEIMAGE:
				// 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
					permissionsUtil = PermissionsUtil
							.with(nAppActivity)
							.requestCode(MY_PERMISSIONS_REQUEST_CAMERA)
							.isDebug(true)
							// 开启log
							.permissions(
									PermissionsUtil.Permission.Camera.CAMERA)
							.request();
				} else {
					ChooseImageDialog();
				}
				break;
			case HANDLER_COMPRESS:
				String strName = (String) msg.obj;
				nAppActivity.SaveImage(strName);
				break;
			case HANDLER_SHAREIMAGE:
				String strmsg1 = (String) msg.obj;
				nAppActivity.ShareImage(strmsg1);
				break;
			case HANDLER_DELIMAGE:
				nAppActivity.DelSelectImage();
				break;
			case HANDLER_DOWNLOAD_APK:
				String apkUrl = (String) msg.obj;
				DownLoadApkHint(apkUrl);
				break;

			case HANDLER_INSTALL_APK:
				String fullApk = (String) msg.obj;
				// 兼容 8.0 无法直接安装
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
					boolean installAllowed = nAppActivity.getPackageManager()
							.canRequestPackageInstalls();
					if (installAllowed) {
						InstallApk(fullApk);
					} else {
						Intent intent = new Intent(
								Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
								Uri.parse("package:"
										+ nAppActivity.getPackageName()));
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						nAppActivity.startActivity(intent);
						InstallApk(fullApk);
						return;
					}

				} else {
					InstallApk(fullApk);
				}
				break;

			case HANDLER_SHOWVERSION:
				String version = (String) msg.obj;
				showversion(version);
				break;

			case HANDLER_SHOWDIALOG:
				dialogTips = ProgressDialog.show(nAppActivity, "提示",
						"正在获取预支付订单...");
				break;

			case HANDLER_CANCELDIALOG:
				if (dialogTips != null) {
					dialogTips.dismiss();
					dialogTips = null;
				}
				break;

			case HANDLER_WECHATPAY:
				IWXAPI msgApi = WXAPIFactory.createWXAPI(nAppActivity, null);
				msgApi.registerApp(Constants.APP_ID);
				PayReq req = (PayReq) msg.obj;
				msgApi.sendReq(req);
				break;

			case HANDLER_OPENWEBVIEW:
				String url = (String) msg.obj;
				nAppActivity.openAndroidView(url);
				break;

			case HANDLER_DOWNLOAD_APK_WITH_NAME:
				String apkname = msg.getData().getString("apkname");
				String apkurl = msg.getData().getString("apkurl");
				DownLoadApkHint1(apkname, apkurl);
				break;

			case HANDLER_ZHIYIFU:
				// StartThirdPay mThirdPay = new StartThirdPay(nAppActivity);
				// mThirdPay.start("100");

				break;

			case HANDLER_YINLIAN:
				final String serverMode = "00";
				String tn = (String) msg.obj;
				break;

			case HANDLER_SHARE: {
				String strmsg = (String) msg.obj;
				nAppActivity.ShareFriend(strmsg);
			}
				break;
			case HANDLER_WXLogin: {
				// String strmsg = (String)msg.obj;
				nAppActivity.WXLogin();
			}
				break;
			}
		}
	};

	private void ShareImage(String img) {

		try {
			BitmapFactory.Options bo = new BitmapFactory.Options();
			bo.inPreferredConfig = Bitmap.Config.ARGB_8888;
			// Bitmap bmp = BitmapFactory.decodeFile(img);
			Bitmap bmp = BitmapFactory.decodeFile(img, bo);
			Log.d("sdk", "路径:" + img);
			WXImageObject imgobj = new WXImageObject(bmp);
			WXMediaMessage msg = new WXMediaMessage();
			msg.mediaObject = imgobj;
			Log.d("sdk", "w=" + bmp.getWidth() + ",h=" + bmp.getHeight()
					+ ",b:" + bmp.getRowBytes() * bmp.getHeight() + ",ast:"
					+ getClass().getResourceAsStream("/a"));
			Bitmap thumbBmp = null;//
			int w = 190;
			int h = 110;

			thumbBmp = Bitmap.createScaledBitmap(bmp, 134, 77, true);
			Log.d("sdk大小", thumbBmp.getByteCount() + ",w=" + w + ",h=" + h);
			for (; thumbBmp.getByteCount() > 42000;) {// 84000;){
				thumbBmp = Bitmap.createScaledBitmap(bmp, w *= 0.99, h *= 0.99,
						true);
				Log.d("sdk大小", thumbBmp.getByteCount() + ",w=" + w + ",h=" + h);
			}

			msg.thumbData = Util.bmpToByteArray(thumbBmp, true);
			Log.d("sdk", "4:" + shareType);
			SendMessageToWX.Req req = new SendMessageToWX.Req();
			req.transaction = "image" + System.currentTimeMillis();
			Log.d("sdk", "time:" + System.currentTimeMillis());
			req.message = msg;
			req.scene = shareType;

			IWXAPI api = WXAPIFactory.createWXAPI(nAppActivity,
					Constants.APP_ID);
			api.sendReq(req);
			if (bmp != null && !bmp.isRecycled()) {
				// 回收并且置为null
				bmp.recycle();
				bmp = null;
			}
			if (thumbBmp != null && !thumbBmp.isRecycled()) {
				// 回收并且置为null
				thumbBmp.recycle();
				thumbBmp = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.d("sdk", "微信错误");
		}

	}

	// 分享图片给微信好友
	public static void shareWeixinImageToFriend(String imagePath, String Type) {
		shareType = Integer.parseInt(Type);
		IWXAPI api = WXAPIFactory.createWXAPI(nAppActivity, Constants.APP_ID);
		if (!api.isWXAppInstalled()) {
			ToShowToast("您还未安装微信客户端");
			return;
		}

		if (imagePath.contains("InviteScreenShot")) {
			imagePath = Environment.getExternalStorageDirectory()
					.getAbsolutePath()
					+ File.separator
					+ "InviteScreen"
					+ File.separator + "InviteScreenShot.jpg";
			Log.d("shareWeixinImageToFriend", "shareWeixinImageToFriend"
					+ imagePath);
		}

		Message msg = new Message();
		msg.what = HANDLER_SHAREIMAGE;
		msg.obj = imagePath;
		handler.sendMessage(msg);
	}

	public static void ToShowToast(String hint) {
		Message msg = new Message();
		msg.what = HANDLER_HINT_MSG;
		msg.obj = hint;
		handler.sendMessage(msg);
	}

	public static void openWebView(String hint) {
		Message msg = new Message();
		msg.what = HANDLER_OPENWEBVIEW;
		msg.obj = hint;
		handler.sendMessage(msg);
	}

	public static void UserLogin(String account) {
		Log.d("userLogin", account);
	}

	public static void restartApp() {
		final Intent intent = nAppActivity.getPackageManager()
				.getLaunchIntentForPackage(nAppActivity.getPackageName());
		PendingIntent restartIntent = PendingIntent.getActivity(nAppActivity,
				0, intent, PendingIntent.FLAG_ONE_SHOT);
		AlarmManager mgr = (AlarmManager) nAppActivity
				.getSystemService(Context.ALARM_SERVICE);
		mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 200,
				restartIntent);
		nAppActivity.finish();
		System.exit(0);
		android.os.Process.killProcess(0);
		;
	}

	// 打开微信
	public static void OpenWeChat() {
		IWXAPI api = WXAPIFactory.createWXAPI(nAppActivity, null);
		boolean sIsWXAppInstalledAndSupported = api.isWXAppInstalled()
				&& api.getWXAppSupportAPI() >= com.tencent.mm.opensdk.constants.Build.TIMELINE_SUPPORTED_SDK_INT;
		if (!sIsWXAppInstalledAndSupported) {
			ToShowToast("微信客户端未安装");
			return;
		}
		Log.d("userLogin", "OpenWeChat");
		Intent intent = new Intent();
		intent.setComponent(new ComponentName("com.tencent.mm",
				"com.tencent.mm.ui.LauncherUI"));
		intent.setAction(Intent.ACTION_VIEW);
		nAppActivity.startActivity(intent);
	}

	public static String getErrorInfoFromException(Exception e) {
		try {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			return "\r\n" + sw.toString() + "\r\n";
		} catch (Exception e2) {
			return "bad getErrorInfoFromException";
		}
	}

	public static void WeiXinLogin() {
		IWXAPI api = WXAPIFactory.createWXAPI(nAppActivity, Constants.APP_ID);
		if (!api.isWXAppInstalled()) {
			ToShowToast("您还未安装微信客户端");
			return;
		}

		Message msg = new Message();
		msg.what = HANDLER_WXLogin;
		handler.sendMessage(msg);
	}

	// 分享朋友圈
	public static void share2weixin(String flag) throws JSONException {
		IWXAPI api = WXAPIFactory.createWXAPI(nAppActivity, Constants.APP_ID);
		if (!api.isWXAppInstalled()) {
			ToShowToast("您还未安装微信客户端");
			return;
		}

		Message msg = new Message();
		msg.what = HANDLER_SHARE;
		msg.obj = flag;
		handler.sendMessage(msg);
	}

	// 获取是否安装微信
	public static String getIsWeChatInstall() {
		IWXAPI api = WXAPIFactory.createWXAPI(nAppActivity, null);
		boolean sIsWXAppInstalledAndSupported = api.isWXAppInstalled()
				&& api.getWXAppSupportAPI() >= com.tencent.mm.opensdk.constants.Build.TIMELINE_SUPPORTED_SDK_INT;
		if (!sIsWXAppInstalledAndSupported) {
			return "false";
		}
		return "true";
	}

	public static long getFileSize(File file) throws Exception {
		long size = 0;
		if (file.exists()) {
			FileInputStream fis = null;
			fis = new FileInputStream(file);
			size = fis.available();
		} else {
			file.createNewFile();
			Log.e("获取文件大小", "文件不存在!");
		}
		return size;
	}

	// ======================================返回的消息处理===========================================
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.e("xiangce", "requestCode::" + requestCode);
		if (requestCode == REQUEST_CODE_GETIMAGE_BYSDCARD) {
			Log.e("xiangce", "选取图片返回");
			if (data != null) {
				Uri selectedImage = data.getData();
				String uriStr = selectedImage.toString();
				Log.d("xiangce", uriStr);
				if (selectedImage != null) {

					String path = MyUtil.getPath(nAppActivity, selectedImage);
					File picture = new File(path);
					// startPhotoZoom(Uri.fromFile(picture));
					Log.e("xiangce", "path=" + path + ":"
							+ nAppActivity.selectImageIndex);
					long size = 0;
					try {
						size = nAppActivity.getFileSize(picture);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (nAppActivity.selectImageIndex != 0) {
						if (size / 1024 > 2048) {
							// ToShowToast("图片文件过大");
							BitmapFactory.Options newOpts = new BitmapFactory.Options();
							// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
							newOpts.inJustDecodeBounds = true;
							Bitmap bitmap = BitmapFactory.decodeFile(path,
									newOpts);// 此时返回bm为空
							newOpts.inJustDecodeBounds = false;
							int w = newOpts.outWidth;
							int h = newOpts.outHeight;
							// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
							float hh = 800f;// 这里设置高度为800f
							float ww = 480f;// 这里设置宽度为480f
							// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
							int be = 1;// be=1表示不缩放
							if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
								be = (int) (newOpts.outWidth / ww);
							} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
								be = (int) (newOpts.outHeight / hh);
							}
							if (be <= 0)
								be = 1;
							newOpts.inSampleSize = be;// 设置缩放比例
							// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
							bitmap = BitmapFactory.decodeFile(path, newOpts);
							if (bitmap != null) {
								SaveBmpAndReturn(bitmap);
							}
						} else {
							Bitmap bitmap1 = BitmapFactory.decodeFile(path);
							SaveBmpAndReturn(bitmap1);
						}
					} else {
						if (uritempFile != null) {
							String path1 = MyUtil.getPath(nAppActivity,
									uritempFile);
							deletefile(path1);
						}
						final Intent intent1 = new Intent(
								"com.android.camera.action.CROP");
						intent1.setDataAndType(
								getImageContentUri(nAppActivity, picture),
								IMAGE_UNSPECIFIED);
						intent1.putExtra("crop", "true");
						intent1.putExtra("aspectX", 1);
						intent1.putExtra("aspectY", 1);
						intent1.putExtra("outputX", CLIP_ASPECT_X);
						intent1.putExtra("outputY", CLIP_ASPECT_Y);
						intent1.putExtra("return-data", true);

						uritempFile = Uri.parse("file://"
								+ "/"
								+ Environment.getExternalStorageDirectory()
										.getPath() + "/" + "small.jpg");
						intent1.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
						intent1.putExtra("outputFormat",
								Bitmap.CompressFormat.JPEG.toString());

						startActivityForResult(intent1,
								REQUEST_CODE_CLIPIMAGE_BYSDCARD);
					}
				}
			}
		}
		// 拍摄图片
		else if (requestCode == REQUEST_CODE_GETIMAGE_BYCAMERA) {
			if (resultCode != RESULT_OK) {

				return;
			}

			// 设置文件保存路径这里放在跟目录下
			File picture = new File(Environment.getExternalStorageDirectory()
					+ "/temp.jpg");
			Log.i("NekoTest", "startPhotoZoom" + nAppActivity.selectImageIndex);

			long size = 0;
			try {
				size = nAppActivity.getFileSize(picture);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (nAppActivity.selectImageIndex != 0) {
				if (size / 1024 > 2048) {
					// ToShowToast("图片文件过大");
					BitmapFactory.Options newOpts = new BitmapFactory.Options();
					// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
					newOpts.inJustDecodeBounds = true;
					Bitmap bitmap = BitmapFactory.decodeFile(
							Environment.getExternalStorageDirectory()
									+ "/temp.jpg", newOpts);// 此时返回bm为空
					newOpts.inJustDecodeBounds = false;
					int w = newOpts.outWidth;
					int h = newOpts.outHeight;
					// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
					float hh = 800f;// 这里设置高度为800f
					float ww = 480f;// 这里设置宽度为480f
					// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
					int be = 1;// be=1表示不缩放
					if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
						be = (int) (newOpts.outWidth / ww);
					} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
						be = (int) (newOpts.outHeight / hh);
					}
					if (be <= 0)
						be = 1;
					newOpts.inSampleSize = be;// 设置缩放比例
					// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
					bitmap = BitmapFactory.decodeFile(
							Environment.getExternalStorageDirectory()
									+ "/temp.jpg", newOpts);
					if (bitmap != null) {
						SaveBmpAndReturn(bitmap);
					}
				} else {
					Bitmap bitmap1 = BitmapFactory.decodeFile(Environment
							.getExternalStorageDirectory() + "/temp.jpg");
					SaveBmpAndReturn(bitmap1);
				}
			} else {
				startPhotoZoom(picture);
			}

		} else if (requestCode == REQUEST_CODE_CLIPIMAGE_BYSDCARD) {
			if (uritempFile != null) {
				String path1 = MyUtil.getPath(nAppActivity, uritempFile);
				File file = new File(path1);
				if (!file.exists()) {
					return;
				}
				Log.e("uritempFile", "图片存在");
				// Bitmap bmp = data.getParcelableExtra("data");
				Bitmap bmp = null;
				try {
					bmp = BitmapFactory.decodeStream(nAppActivity
							.getContentResolver().openInputStream(uritempFile));
					if (bmp != null) {
						SaveBmpAndReturn(bmp);
					}
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		else if (requestCode == REQUEST_CODE_CLIPIMAGE_BYCAMERA) {
			if (uritempFile != null) {
				String path1 = MyUtil.getPath(nAppActivity, uritempFile);
				File file = new File(path1);
				if (!file.exists()) {
					return;
				}
				Log.e("uritempFile", "图片存在");
				// Bitmap bmp = data.getParcelableExtra("data");
				Bitmap bmp = null;
				try {
					bmp = BitmapFactory.decodeStream(nAppActivity
							.getContentResolver().openInputStream(uritempFile));
					if (bmp != null) {
						SaveBmpAndReturn(bmp);
					}
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} else if (requestCode == REQUEST_CODE_SCANNIN_GREQUEST) {
			if (resultCode == RESULT_OK) {
				Bundle bundle = data.getExtras();
				// 显示扫描到的内容
				String resultStr = bundle.getString("result");
				Log.i("NekoTest", "The QR Code is " + resultStr);
				ScanQRCodeReturn(resultStr);
			}
		} else if (requestCode == REQUEST_CODE_RIGIONALISM) {
			if (resultCode == RESULT_OK) {
				Bundle bundle = data.getExtras();
				String ZipCode = bundle.getString("ZipCode");
				String ProviceName = bundle.getString("Provice");
				String CityName = bundle.getString("City");
				String DistrictName = bundle.getString("District");

				Log.i("NekoTest", "The Index is " + ZipCode + ",The City is "
						+ ProviceName + CityName + DistrictName);

				ReegionalismReturn(ZipCode, ProviceName, CityName, DistrictName);
			}
		} else if (requestCode >= REQUEST_CODE_DOWNLOAD_APK_INDEX_Key) {
			String strPackageName = null;
			if (apkMap_Info != null) {
				strPackageName = apkMap_Info.get(requestCode);
				if (strPackageName != null) {
					apkMap_Info.remove(requestCode);
					changeDownloadState(strPackageName);
					isDownloadApkEnd = true;
				}
			}

		}
	}

	/**
	 * 删除文件，可以是文件或文件夹
	 * 
	 * @param delFile
	 *            要删除的文件夹或文件名
	 * @return 删除成功返回true，否则返回false
	 */
	private boolean deletefile(String delFile) {
		File file = new File(delFile);
		if (!file.exists()) {
			// Toast.makeText(getApplicationContext(), "删除文件失败:" + delFile +
			// "不存在！", Toast.LENGTH_SHORT).show();
			return false;
		} else {
			if (file.isFile())
				return deleteSingleFile(delFile);
			else
				return deleteDirectory(delFile);
		}
	}

	/**
	 * 删除单个文件
	 * 
	 * @param filePath$Name
	 *            要删除的文件的文件名
	 * @return 单个文件删除成功返回true，否则返回false
	 */
	private boolean deleteSingleFile(String filePath$Name) {
		File file = new File(filePath$Name);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				Log.e("--Method--", "Copy_Delete.deleteSingleFile: 删除单个文件"
						+ filePath$Name + "成功！");
				return true;
			} else {
				// Toast.makeText(getApplicationContext(), "删除单个文件" +
				// filePath$Name + "失败！", Toast.LENGTH_SHORT).show();
				return false;
			}
		} else {
			// Toast.makeText(getApplicationContext(), "删除单个文件失败：" +
			// filePath$Name + "不存在！", Toast.LENGTH_SHORT).show();
			return false;
		}
	}

	/**
	 * 删除目录及目录下的文件
	 * 
	 * @param filePath
	 *            要删除的目录的文件路径
	 * @return 目录删除成功返回true，否则返回false
	 */
	private boolean deleteDirectory(String filePath) {
		// 如果dir不以文件分隔符结尾，自动添加文件分隔符
		if (!filePath.endsWith(File.separator))
			filePath = filePath + File.separator;
		File dirFile = new File(filePath);
		// 如果dir对应的文件不存在，或者不是一个目录，则退出
		if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
			// Toast.makeText(getApplicationContext(), "删除目录失败：" + filePath +
			// "不存在！", Toast.LENGTH_SHORT).show();
			return false;
		}
		boolean flag = true;
		// 删除文件夹中的所有文件包括子目录
		File[] files = dirFile.listFiles();
		for (File file : files) {
			// 删除子文件
			if (file.isFile()) {
				flag = deleteSingleFile(file.getAbsolutePath());
				if (!flag)
					break;
			}
			// 删除子目录
			else if (file.isDirectory()) {
				flag = deleteDirectory(file.getAbsolutePath());
				if (!flag)
					break;
			}
		}
		if (!flag) {
			// Toast.makeText(getApplicationContext(), "删除目录失败！",
			// Toast.LENGTH_SHORT).show();
			return false;
		}
		// 删除当前目录
		if (dirFile.delete()) {
			Log.e("--Method--", "Copy_Delete.deleteDirectory: 删除目录" + filePath
					+ "成功！");
			return true;
		} else {
			// Toast.makeText(getApplicationContext(), "删除目录：" + filePath +
			// "失败！", Toast.LENGTH_SHORT).show();
			return false;
		}
	}

	// ======================================获取设备基本信息===========================================
	private static final int SYSSTATE_MACADDRESS = 0;
	private static final int SYSSTATE_BIOSID = 1;
	private static final int SYSSTATE_CUPID = 2;
	private static final int SYSSTATE_HDID = 3;
	private static final int SYSSTATE_VERSION = 4;
	private static final int SYSSTATE_MODEL = 5;
	private static final int SYSSTATE_UUID = 6;
	private static final int SYSSTATE_OAID = 7;

	public static String GetSysInfo(int sysState) {
		String SysInfo = "";
		switch (sysState) {
		case SYSSTATE_MACADDRESS:
			SysInfo = nAppActivity.getLocalMacAddress();
			break;
		case SYSSTATE_BIOSID:
			SysInfo = nAppActivity.getAndroidId();
			break;
		case SYSSTATE_CUPID:
			SysInfo = nAppActivity.getMobileModel();
			break;
		case SYSSTATE_HDID:
			SysInfo = nAppActivity.getDeviceId();
			break;
		case SYSSTATE_VERSION:
			SysInfo = nAppActivity.getSysVersion();
			break;
		case SYSSTATE_MODEL:
			SysInfo = nAppActivity.getMobileModel();
			break;
		case SYSSTATE_UUID:
			SysInfo = nAppActivity.getUUID();
			break;
		case SYSSTATE_OAID:
			SysInfo = nAppActivity.getOAId();
			break;
		}
		// Log.i("NekoTest", "GetSysInfo-----The sysState is " + sysState
		// + ",SysInfo is:" + SysInfo);
		return SysInfo;
	}

	// OperatorsID
	public static long GetOperatorsID() {
		try {
			ApplicationInfo ai = nAppActivity.getPackageManager()
					.getApplicationInfo(nAppActivity.getPackageName(),
							PackageManager.GET_META_DATA);
			Bundle bundle = ai.metaData;
			Object obj = bundle.get("OPERATORSID");
			long returnvalue = ((Integer) obj).longValue();
			return returnvalue;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	// channel
	public static String GetChannel() {
		String str = new String();// getChannel(nAppActivity);
		// if(TextUtils.isEmpty(str))
		{
			try {
				ApplicationInfo ai = nAppActivity.getPackageManager()
						.getApplicationInfo(nAppActivity.getPackageName(),
								PackageManager.GET_META_DATA);
				Bundle bundle = ai.metaData;
				Object obj = bundle.get("UMENG_CHANNEL");
				str = obj.toString();

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		return str;
	}

	public static String GetSDKChannel() {
		return "";
	}

	public static long CheckNetWork(String strurl) {
		ServerUrl = strurl;
		return IsPing ? 1 : 0;
	}

	// DeviceId
	public String getDeviceId() {
		// 需要android.permission.READ_PHONE_STATE权限
		String DEVICE_ID = "";
		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		Log.d(TAG,"Build.VERSION.SDK_INT : " + Build.VERSION.SDK_INT);
		if (Build.VERSION.SDK_INT <= 28) {//P
			DEVICE_ID = tm.getDeviceId();
			Log.d(TAG, "<= 	P  ");
		}else {
			/*因c++传递到服务器超64位会被截断，
			 * 获取唯一标识在此处进行处理
			 * idfa保持原字符串不变
			 */
			DEVICE_ID = getOAId();
			DEVICE_ID = MD5Util.MD5Encode(DEVICE_ID, "");
			Log.d(TAG, "md5 oaid ——>");
		
		}
		Log.d(TAG, "DEVICE_ID : " + DEVICE_ID);
		return DEVICE_ID;
	}
	
	// 移动联盟oaid
	public String getOAId() {
		String oaid = "";
		if (Build.VERSION.SDK_INT > 28) {//P
			Log.d(TAG, "SDK_INT  > 	P");
			oaid = DevicesUtil.getOAID(this);
		}
		Log.d(TAG, "getOAId  : " + oaid);
		return oaid;
	}

	// AndroidId
	// @SuppressWarnings("deprecation")
	public String getAndroidId() {
		// String ANDROID_ID = Settings.System.getString(getContentResolver(),
		// Settings.System.ANDROID_ID);
		String ANDROID_ID = Secure.getString(getContentResolver(),
				Secure.ANDROID_ID);
		// Log.i("NekoTest", "ANDROID_ID is " + ANDROID_ID);
		return ANDROID_ID;
	}

	// Serial Number
	public String getSerialNumber() {
		String SerialNumber = android.os.Build.SERIAL;
		Log.i("NekoTest", "SerialNumber is " + SerialNumber);
		return SerialNumber;
	}

	// cpu号
	public String getCupId() {
		String macSerial = null;
		String str = "";
		try {
			Process pp = Runtime.getRuntime().exec("cat /proc/cpuinfo");
			InputStreamReader ir = new InputStreamReader(pp.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);

			for (; null != str;) {
				str = input.readLine();
				if (str != null) {
					macSerial = str.trim();// 去空格
					break;
				}
			}
		} catch (IOException ex) {
			// 赋予默认值
			ex.printStackTrace();
		}
		return macSerial;
	}

	// 获取Mac地址
	public String getMac() {
		String macSerial = null;
		String str = "";
		try {
			Process pp = Runtime.getRuntime().exec(
					"cat /sys/class/net/wlan0/address");
			InputStreamReader ir = new InputStreamReader(pp.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);

			for (; null != str;) {
				str = input.readLine();
				if (str != null) {
					macSerial = str.trim();// 去空格
					break;
				}
			}
		} catch (IOException ex) {
			// 赋予默认值
			ex.printStackTrace();
		}
		return macSerial;
	}

	// Android 获取本机Mac地址,需要开启wifi
	public String getLocalMacAddress() {
		WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		return info.getMacAddress();
	}

	// Android 获取本机IP地址方法
	public String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			Log.e("WifiPreference IpAddress", ex.toString());
		}
		return null;
	}

	// 获取系统版本号
	public String getSysVersion() {
		String androidVersion = android.os.Build.VERSION.RELEASE;
//		String ANDROID_TAG = getSysProperty("ro.build.display.id");
		String sysVersion = androidVersion;		//+ANDROID_TAG;
		String[]  strs=sysVersion.split("\\.");
		Log.d(TAG,"sysVersion [0] : " + strs[0]);
		
		if (isNumberString(strs[0])) {
			return strs[0];
		}
		return "0";
	}
	
	public static boolean isNumberString(String str) {
		Pattern pattern = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}
	
	// 获取手机型号
	public String getMobileModel() {
		return android.os.Build.MODEL;

	}

	// 获取随机ID
	public String getUUID() {
		Log.d("NekoTest ", "Installation.id(this) is " + Installation.id(this)
				+ " ");
		return Installation.id(this);
	}

	// 获取cpu名字
	public static String getCpuName() {
		try {
			FileReader fr = new FileReader("/proc/cpuinfo");
			BufferedReader br = new BufferedReader(fr);
			String text = br.readLine();
			String[] array = text.split(":\\s+", 2);
			for (int i = 0; i < array.length; i++) {
			}
			return array[1];
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 获取cpu型号
	public static String getCpuModel() {
		try {
			FileReader fr = new FileReader("/proc/cpuinfo");
			BufferedReader br = new BufferedReader(fr);
			String text = null;

			while ((text = br.readLine()) != null) {
				String[] array = text.split(":\\s+", 2);
				for (int i = 0; i < array.length; i++) {
				}
				if (array[0].contains("Hardware")) {
					Log.i("NekoTest", "The Cup is " + array[1]);
					return array[1];
				}
			}

			return null;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	// // 获取cpu序列号
	// public static String getCPUSerial() {
	// try {
	// FileReader fr = new FileReader("/proc/cpuinfo");
	// BufferedReader br = new BufferedReader(fr);
	// String text = null;
	//
	// while((text = br.readLine())!=null){
	// String[] array = text.split(":\\s+", 2);
	// for (int i = 0; i < array.length; i++) {
	// }
	// if(array[0].contains("Serial")){
	// Log.i("NekoTest", "The Cup  Serial is " + array[1]);
	// return array[1];
	// }
	// }
	// return null;
	// } catch (FileNotFoundException e) {
	// e.printStackTrace();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// return null;
	// }

	/**
	 * 获取CPU序列号
	 * 
	 * @return CPU序列号(16位) 读取失败为"0000000000000000"
	 */
	public static String getCPUSerial() {
		String str = "", strCPU = "", cpuAddress = "0000000000000000";
		try {
			// 读取CPU信息
			Process pp = Runtime.getRuntime().exec("cat /proc/cpuinfo");
			InputStreamReader ir = new InputStreamReader(pp.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);
			// 查找CPU序列号
			for (int i = 1; i < 100; i++) {
				str = input.readLine();
				if (str != null) {
					// 查找到序列号所在行
					if (str.indexOf("Serial") > -1) {
						// 提取序列号
						strCPU = str.substring(str.indexOf(":") + 1,
								str.length());
						// 去空格
						cpuAddress = strCPU.trim();
						break;
					}
				} else {
					// 文件结尾
					break;
				}
			}
		} catch (IOException ex) {
			// 赋予默认值
			ex.printStackTrace();
		}
		// Log.i("NekoTest", "The Cup Serial is " + cpuAddress);
		return cpuAddress;
	}

	// 获取系统属性值----系统反射
	public String getSysProperty(String key) {
		Class<?> clazz;
		try {
			clazz = Class.forName("android.os.SystemProperties");
			Method method = clazz.getDeclaredMethod("get", String.class);
			return (String) method.invoke(clazz.newInstance(), key);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static void useBrownStartUrl(String url){
        try{
        	Intent mIntent = new Intent(Intent.ACTION_VIEW);
        	mIntent.setData(Uri.parse(url));
            nAppActivity.startActivity(mIntent);
        }
        catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)          
        }
    }

	// ======================================扫描二维码===========================================

	// 开始扫描
	public static void StartScanQRCode() {
		nAppActivity.scanQRCode();
	}

	public void scanQRCode() {
		// 切换到照相界面
		Intent intent = new Intent();
		intent.setClass(AppActivity.getContext(), CaptureActivity.class);
		this.startActivityForResult(intent, REQUEST_CODE_SCANNIN_GREQUEST);
	}

	// java调用cocos2d-x的地方
	// 二维码扫描返回
	public static native void ScanQRCodeReturn(final String msg);
	// ======================================选择图片===========================================

	public static final String IMAGE_UNSPECIFIED = "image/*";
	private static final int CLIP_ASPECT_X = 240;
	private static final int CLIP_ASPECT_Y = 240;

	public static void ToSelectIcon() {
		selectImageIndex = 0;
		Message msg = new Message();
		msg.what = HANDLER_IMAGE_CHOOSE;
		msg.obj = "";
		handler.sendMessage(msg);
	}
	//android选择图片反馈
	public static void AdChooseImage(String hint) {
		
		selectImageIndex = Integer.parseInt(hint);  
		Message msg = new Message();
		msg.what = HANDLER_CHOOSEIMAGE;
		msg.obj = hint;
		handler.sendMessage(msg);
	}
	//android删除图片反馈
	public static void AdDelImage(String hint,String hint1) {
		delSelectImage = Integer.parseInt(hint);  
		maxSelectImage = Integer.parseInt(hint1);
		Message msg = new Message();
		msg.what = HANDLER_DELIMAGE;
		msg.obj = hint;
		handler.sendMessage(msg);
	}

	public void DelSelectImage() {
		String picName1 = "";
		String picName2 = "";
		for (int i = delSelectImage; i < maxSelectImage; i++) {
			int t_index1 = i + 2;
			int t_index2 = i + 1;
			if (t_index1 <= maxSelectImage) {

				picName1 = getContext().getFilesDir() + "/" + "MyIcon_"
						+ t_index1 + ".jpg";
				picName2 = "MyIcon_" + t_index2 + ".jpg";
				Bitmap bitmap1 = null;

				// File file = new File(picName1);
				// if(bitmap1.)
				// if(file.exists())
				{

					bitmap1 = BitmapFactory.decodeFile(picName1);

					int w = bitmap1.getWidth();// 190;
					int h = bitmap1.getHeight();
					bitmap1 = Bitmap.createScaledBitmap(bitmap1, w, h, true);
					Log.d("sdk大小", bitmap1.getByteCount() + ",w=" + w + ",h="
							+ h);
					// for(;bitmap1.getByteCount()>200000;){
					// bitmap1=Bitmap.createScaledBitmap(bitmap1, w*=0.99,
					// h*=0.99, true);
					// Log.d("sdk大小",bitmap1.getByteCount()+",w="+w+",h="+h);
					// }

					try {
						FileOutputStream out = openFileOutput(picName2,
								MODE_PRIVATE);
						bitmap1.compress(Bitmap.CompressFormat.PNG, 100, out);
						out.flush();
						out.close();
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		/*
		 * for(int i=delSelectImage;i<5;i++) { if( i+1<5) { //saveBitMap[0] =
		 * saveBitMap[1]; } }
		 */
		IconDelReturn("");
	}

	// 弹出选择图片的选择框
	public static void ChooseImageDialog() {
		CharSequence[] items = { "手机相册", "手机拍照", "取消" };
		AlertDialog imageDialog = new AlertDialog.Builder(getContext())
				.setTitle("选择图片")
				.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						if (item == REQUEST_CODE_GETIMAGE_BYSDCARD) {
							// 手机选图
							Log.d("xiangce", "手机选图");
							Intent intent = new Intent(
									Intent.ACTION_GET_CONTENT);
							intent.setType("image/*");
							nAppActivity.startActivityForResult(intent,
									REQUEST_CODE_GETIMAGE_BYSDCARD);

						}
						// 拍照
						else if (item == REQUEST_CODE_GETIMAGE_BYCAMERA) {
							Intent intentC = new Intent(
									MediaStore.ACTION_IMAGE_CAPTURE);
							Uri photoUri = FileProvider.getUriForFile(
									nAppActivity,
									nAppActivity.getPackageName()
											+ ".fileprovider",
									new File(Environment
											.getExternalStorageDirectory(),
											"temp.jpg"));
							intentC.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);

							nAppActivity.startActivityForResult(intentC,
									REQUEST_CODE_GETIMAGE_BYCAMERA);
						}
					}
				}).create();
		imageDialog.show();
	}

	public static Uri getImageContentUri(Context context, File imageFile) {
		String filePath = imageFile.getAbsolutePath();
		Cursor cursor = context.getContentResolver().query(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				new String[] { MediaStore.Images.Media._ID },
				MediaStore.Images.Media.DATA + "=? ",
				new String[] { filePath }, null);
		if (cursor != null && cursor.moveToFirst()) {
			int id = cursor.getInt(cursor
					.getColumnIndex(MediaStore.MediaColumns._ID));
			Uri baseUri = Uri.parse("content://media/external/images/media");
			return Uri.withAppendedPath(baseUri, "" + id);
		} else {
			if (imageFile.exists()) {
				ContentValues values = new ContentValues();
				values.put(MediaStore.Images.Media.DATA, filePath);
				return context.getContentResolver().insert(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
			} else {
				return null;
			}
		}
	}

	public void startPhotoZoom(File picture) {
		System.out.println(picture);
		Log.i("NekoTest", "File:" + picture);
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(getImageContentUri(nAppActivity, picture),
				IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", CLIP_ASPECT_X);
		intent.putExtra("outputY", CLIP_ASPECT_Y);
		intent.putExtra("return-data", true);

		if (uritempFile != null) {
			String path1 = MyUtil.getPath(nAppActivity, uritempFile);
			deletefile(path1);
		}
		uritempFile = Uri.parse("file://" + "/"
				+ Environment.getExternalStorageDirectory().getPath() + "/"
				+ "small.jpg");
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

		startActivityForResult(intent, REQUEST_CODE_CLIPIMAGE_BYCAMERA);
	}

	public void SaveImage(String img) {
		String picName = getContext().getFilesDir() + "/" + "ScreenShot.jpg";
		String picName1 = "ScreenShot1.jpg";
		Bitmap thumbBmp = BitmapFactory.decodeFile(picName);

		Log.d("sdk", "w=" + thumbBmp.getWidth() + ",h=" + thumbBmp.getHeight()
				+ ",b:" + thumbBmp.getRowBytes() * thumbBmp.getHeight()
				+ ",ast:");
		saveImageToGallery(nAppActivity, thumbBmp);
		// Bitmap thumbBmp = null;//
		// int w = thumbBmp.getWidth();// 190;
		// int h = thumbBmp.getHeight();// 110;
		// if (w > 1024) {
		// w = 1024;
		// }
		// if (h > 720) {
		// h = 720;
		// }
		// thumbBmp =
		// BitmapFactory.decodeFile(picName);//Bitmap.createScaledBitmap(thumbBmp,
		// w, h, true);
		// Log.d("sdk大小", thumbBmp.getByteCount() + ",w=" + w + ",h=" + h);
		// for(;thumbBmp.getByteCount()>200000;){
		// thumbBmp=Bitmap.createScaledBitmap(thumbBmp, w*=0.99, h*=0.99, true);
		// Log.d("sdk大小",thumbBmp.getByteCount()+",w="+w+",h="+h);
		// }
		// 设置文件保存路径这里放在跟目录下
		File picture = new File(picName);
		Log.i("NekoTest", "startPhotoZoom" + nAppActivity.selectImageIndex);

		long size = 0;
		try {
			size = nAppActivity.getFileSize(picture);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (size / 1024 > 300) {
			Log.d("test error 1", "+" + size);
			// ToShowToast("图片文件过大");
			BitmapFactory.Options newOpts = new BitmapFactory.Options();
			// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
			newOpts.inJustDecodeBounds = true;
			thumbBmp = BitmapFactory.decodeFile(picName, newOpts);// 此时返回bm为空
			newOpts.inJustDecodeBounds = false;
			int w1 = newOpts.outWidth;
			int h1 = newOpts.outHeight;
			// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
			int hh = 200;// 这里设置高度为800f
			int ww = 120;// 这里设置宽度为480f
			// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
			int be = 1;// be=1表示不缩放
			if (w1 > h1 && w1 > ww) {// 如果宽度大的话根据宽度固定大小缩放
				be = (int) (newOpts.outWidth / ww);
			} else if (w1 < h1 && h1 > hh) {// 如果高度高的话根据宽度固定大小缩放
				be = (int) (newOpts.outHeight / hh);
			}
			if (be <= 0)
				be = 1;
			newOpts.inSampleSize = be;// 设置缩放比例
			// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
			thumbBmp = BitmapFactory.decodeFile(picName, newOpts);
			thumbBmp = Bitmap.createScaledBitmap(thumbBmp, ww, hh, true);
			Log.d("test error 1", "+");
			// SaveBmpAndReturn(bitmap1);
		} else {
			Log.d("test error 2", "+");
			// Bitmap thumbBmp = null;//
			int w = thumbBmp.getWidth();// 190;
			int h = thumbBmp.getHeight();// 110;
			if (w > 1024) {
				w = 1024;
			}
			if (h > 720) {
				h = 720;
			}
			thumbBmp = Bitmap.createScaledBitmap(thumbBmp, w, h, true);
		}

		try {

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			thumbBmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
			int options = 100;
			while (baos.toByteArray().length / 1024 > 100 && options > 0) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
				baos.reset(); // 重置baos即清空baos
				thumbBmp.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
				options -= 10;// 每次都减少10
			}

			// int w = thumbBmp.getWidth();// 190;
			// int h = thumbBmp.getHeight();// 110;
			// for(;thumbBmp.getByteCount()>200000;){
			// thumbBmp=Bitmap.createScaledBitmap(thumbBmp, w*=0.99,
			// h*=0.99, true);

			// }

			FileOutputStream out = openFileOutput(picName1, MODE_PRIVATE);
			thumbBmp.compress(Bitmap.CompressFormat.JPEG, options, out);
			out.flush();
			out.close();
			File picture1 = new File(getContext().getFilesDir() + "/"
					+ picName1);
			long size1 = 0;
			try {
				size1 = nAppActivity.getFileSize(picture1);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.d("test error 3", "+" + size1);
			IconCompressReturn(img);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private InputStream getInput() {
		// TODO Auto-generated method stub
		return null;
	}

	private void doDraw(int i, Canvas canvas) {
		// TODO Auto-generated method stub

	}

	public static void AdCompressImage(String img) {
		// /
		// selectImageIndex = hint;
		Message msg = new Message();
		msg.what = HANDLER_COMPRESS;
		msg.obj = img;
		handler.sendMessage(msg);
		// //
	}

	public void SaveBmpAndReturn(Bitmap bmp) {
		if (selectImageIndex > 5)
			return;
		BitmapFactory.Options bo = new BitmapFactory.Options();
		bo.inPreferredConfig = Bitmap.Config.ARGB_8888;
		String picName = "MyIcon.png";
		if (selectImageIndex != 0) {
			picName = "MyIcon_" + selectImageIndex + ".jpg";

			Log.d("tag", "error test 1");
			int w = bmp.getWidth();// 190;
			int h = bmp.getHeight();// 110;
			if (w > 1024) {
				w = 1024;
			}
			if (h > 720) {
				h = 720;
			}

			bmp = Bitmap.createScaledBitmap(bmp, w, h, true);
			Log.d("sdk大小", bmp.getByteCount() + ",w=" + w + ",h=" + h);
			// for(;bmp.getByteCount()>200000;){
			// bmp=Bitmap.createScaledBitmap(bmp, w*=0.99, h*=0.99, true);
			// Log.d("sdk大小",bmp.getByteCount()+",w="+w+",h="+h);
			// }

		}

		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
			int options = 100;
			while (baos.toByteArray().length / 1024 > 100 && options > 0) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
				baos.reset(); // 重置baos即清空baos
				bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
				options -= 10;// 每次都减少10
			}
			FileOutputStream out = openFileOutput(picName, MODE_PRIVATE);
			bmp.compress(Bitmap.CompressFormat.JPEG, options, out);
			out.flush();
			out.close();
			Log.d("tag", "error test 2");
			if (selectImageIndex != 0) {
				Log.i("xiangce1", "已经保存");
				IconSelectReturn1(picName);
			} else {
				Log.i("xiangce2", "已经保存");
				IconSelectReturn(picName);
			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void saveImageToGallery(Context context, Bitmap bmp) {
		// 首先保存图片
		File appDir = new File(Environment.getExternalStorageDirectory(),
				"ScreenPic");
		if (!appDir.exists()) {
			appDir.mkdir();
		}
		String fileName = System.currentTimeMillis() + ".jpg";
		File file = new File(appDir, fileName);
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
			int options = 100;
			while (baos.toByteArray().length / 1024 > 2048) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
				baos.reset(); // 重置baos即清空baos
				bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
				options -= 10;// 每次都减少10
			}

			FileOutputStream fos = new FileOutputStream(file);
			bmp.compress(CompressFormat.JPEG, options, fos);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 最后通知图库更新
		context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
				Uri.fromFile(new File(file.getPath()))));
	}

	// java调用cocos2d-x的地方
	// 选择图片扫描返回，返回值为生成的图片名字，需要一段时间写入才能读取
	public static native void IconSelectReturn(final String msg);

	// 选择反馈图片
	public static native void IconSelectReturn1(final String msg);

	// 删除反馈图片
	public static native void IconDelReturn(final String msg);

	// 压缩屏幕截图
	public static native void IconCompressReturn(final String msg);

	// ======================================选择地址的行政区域===========================================
	// 地址行政区域选择
	public static void ToSelectReegionalism() {
		// 切换到选择行政区域界面
		Intent intent = new Intent();
		intent.setClass(AppActivity.getContext(), RegionActivity.class);
		nAppActivity.startActivityForResult(intent, REQUEST_CODE_RIGIONALISM);
	}

	// 行政区域信息返回
	public static native void ReegionalismReturn(final String ZipCode,
			final String Provice, final String City, final String District);

	// ======================================手机震动===========================================
	public static boolean bShake = false;

	public static void StartShake(String msg) {
		try {
			if (msg.equals("1")) {
				if (!bShake) {
					bShake = true;
					Vibrator vib = (Vibrator) nAppActivity
							.getSystemService(Service.VIBRATOR_SERVICE);
					vib.vibrate(new long[] { 300, 500 }, 0);
				}
			} else {
				if (bShake) {
					bShake = false;
					Vibrator vib = (Vibrator) nAppActivity
							.getSystemService(Service.VIBRATOR_SERVICE);
					vib.cancel();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// ======================================获取版本号===========================================
	public static String GetAppVersion() {
		return getVersionName(nAppActivity);
	}

	// 版本名
	public static String getVersionName(Context context) {
		return getPackageInfo(context).versionName;
	}

	// 版本号
	public static int getVersionCode(Context context) {
		return getPackageInfo(context).versionCode;
	}

	private static PackageInfo getPackageInfo(Context context) {

		PackageInfo pi = null;

		try {
			PackageManager pm = context.getPackageManager();
			pi = pm.getPackageInfo(context.getPackageName(),
					PackageManager.GET_CONFIGURATIONS);

			return pi;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return pi;
	}

	// 版本名
	public static String getPakName() {
		return getAppPkgName(nAppActivity);
	}

	public static String getAppPkgName(Context context) {
		return context.getPackageName();
	}

	// ======================================检查apk是否安装===========================================
	public static int GetAppInstalled(String apkname) {
		return getIsPackageInstall(nAppActivity, apkname);
	}

	private static int getIsPackageInstall(Context context, String apkname) {

		PackageInfo pi = null;
		int result = 0;

		try {
			PackageManager pm = context.getPackageManager();
			pi = pm.getPackageInfo(apkname, 0);

			if (pi == null) {
				result = 0;
			} else {
				result = 1;
				Intent intent = context.getPackageManager()
						.getLaunchIntentForPackage(apkname);
				if (intent != null)
					// 已安装包 直接启动
					context.startActivity(intent);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = 0;
		}

		return result;
	}

	// ======================================apk更新===========================================
	// 需要下载apk
	public static void ToDownLoadApk(String apkUrl) {
		Message msg = new Message();
		msg.what = HANDLER_DOWNLOAD_APK;
		msg.obj = apkUrl;
		handler.sendMessage(msg);
	}

	// 安装程序
	public static void InstallUpdateFile(String fullapk) {
		Message msg = new Message();
		msg.what = HANDLER_INSTALL_APK;
		msg.obj = fullapk;
		handler.sendMessage(msg);
	}

	protected static native void changeDownloadState(final String apkName);

	// 下载APK并返回包名进度
	public static void DownloadApkWithName(String apkName, String apkUrl) {
		Message msg = new Message();
		Bundle bundle = new Bundle();
		bundle.putString("apkname", apkName);
		bundle.putString("apkurl", apkUrl);
		msg.what = HANDLER_DOWNLOAD_APK_WITH_NAME;
		// msg.obj = apkUrl;
		msg.setData(bundle);
		handler.sendMessage(msg);
	}

	public static void ToShowVersion(String version) {
		Message msg = new Message();
		msg.what = HANDLER_SHOWVERSION;
		msg.obj = version;
		handler.sendMessage(msg);
	}

	// 弹出选择图片的选择框
	public static void DownLoadApkHint(String apkUrl) {
		// Log.e("NekoTest", "apk下载地址是"+apkUrl);
		ApkUpdate apkUpdate = new ApkUpdate();
		apkUpdate.ToDownLoadApk(nAppActivity.getContext(), apkUrl);
	}

	// 安装apk
	public static void InstallApk(String fullApk) {
		ApkUpdate apkUpdate = new ApkUpdate();
		apkUpdate.InstallApk(nAppActivity.getContext(), fullApk);
	}

	public static void DownLoadApkHint1(String apkname, String apkUrl) {
		// Log.e("NekoTest", "apk下载地址是"+apkUrl);
		ApkUpdate apkUpdate = new ApkUpdate();
		int size = apkMap_Info.size();
		int key = REQUEST_CODE_DOWNLOAD_APK_INDEX_Key + size;
		apkMap_Info.put(key, apkname);
		isDownloadApkEnd = false;
		apkUpdate.DownLoadApkWithName(nAppActivity.getContext(), apkname, key,
				apkUrl);
	}

	public static void showversion(String version) {
		AlertDialog.Builder builer = new Builder(nAppActivity.getContext());
		builer.setTitle("提示");
		// builer.setMessage("检查到最新版本，请及时升级");
		builer.setMessage("当前版本号" + version);

		// 当点取消按钮则关闭应用
		builer.setNegativeButton("取消", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		AlertDialog dialog = builer.create();
		dialog.show();
	}

	// ======================================获取电池电量===========================================
	private BroadcastReceiver batteryLevelRcvr = null;
	private static boolean bHaveMonitorBattery = false; // 是否开启电量监听
	private IntentFilter batteryLevelFilter;

	@Override
	protected void onDestroy() {
		mShaker.stop();
		super.onDestroy();
		if (batteryLevelRcvr != null)
			unregisterReceiver(batteryLevelRcvr);
	}

	public static void ToMonitorBattery() {
		if (bHaveMonitorBattery)
			return;
		bHaveMonitorBattery = true;
		nAppActivity.monitorBatteryState();
	}

	private void monitorBatteryState() {
		if (batteryLevelRcvr != null)
			return;
		batteryLevelRcvr = new BroadcastReceiver() {
			public void onReceive(Context context, Intent intent) {

				int rawlevel = intent.getIntExtra("level", -1);
				int scale = intent.getIntExtra("scale", -1);
				int status = intent.getIntExtra("status", -1);
				int health = intent.getIntExtra("health", -1);
				int level = 100; // percentage, or -1 for unknown
				if (rawlevel >= 0 && scale > 0) {
					level = (rawlevel * 100) / scale;
				}
				// Log.e("NekoTest", "电池电量是-----"+level);
				BatteryReturn(level);

				final String action = intent.getAction();
				if (action.equalsIgnoreCase(Intent.ACTION_BATTERY_CHANGED)) {
					switch (health) {
					case BatteryManager.BATTERY_HEALTH_COLD:
						// System.out.println("BATTERY_HEALTH_COLD");
						break;
					case BatteryManager.BATTERY_HEALTH_DEAD:
						// System.out.println("BATTERY_HEALTH_DEAD ");
						break;
					case BatteryManager.BATTERY_HEALTH_GOOD:
						// System.out.println("BATTERY_HEALTH_GOOD");
						break;
					case BatteryManager.BATTERY_HEALTH_OVERHEAT:
						// System.out.println("BATTERY_HEALTH_OVERHEAT");
						break;
					case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
						// System.out.println("BATTERY_HEALTH_COLD");
						break;
					case BatteryManager.BATTERY_HEALTH_UNKNOWN:
						// System.out.println("BATTERY_HEALTH_UNKNOWN");
						break;
					case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
						// System.out.println("BATTERY_HEALTH_UNSPECIFIED_FAILURE");
						break;
					default:
						break;
					}

					// 当前手机使用的是哪里的电源
					int pluged = intent.getIntExtra(
							BatteryManager.EXTRA_PLUGGED, -1);
					switch (pluged) {
					case BatteryManager.BATTERY_PLUGGED_AC:
						// 电源是AC charger.[应该是指充电器]
						// System.out.println("BATTERY_PLUGGED_AC");
						break;
					case BatteryManager.BATTERY_PLUGGED_USB:
						// 电源是USB port
						// System.out.println("BATTERY_PLUGGED_USB ");
						break;
					default:
						break;
					}

					switch (status) {
					case BatteryManager.BATTERY_STATUS_CHARGING:
						// 正在充电
						// System.out.println("BATTERY_STATUS_CHARGING ");
						break;
					case BatteryManager.BATTERY_STATUS_DISCHARGING:
						// System.out.println("BATTERY_STATUS_DISCHARGING  ");
						break;
					case BatteryManager.BATTERY_STATUS_FULL:
						// 充满
						// System.out.println("BATTERY_STATUS_FULL ");
						break;
					case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
						// 没有充电
						// System.out.println("BATTERY_STATUS_NOT_CHARGING ");
						break;
					case BatteryManager.BATTERY_STATUS_UNKNOWN:
						// 未知状态
						// System.out.println("BATTERY_STATUS_UNKNOWN ");
						break;
					default:
						break;
					}
					// 电池使用的技术。比如，对于锂电池是Li-ion
					String technology = intent
							.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY);
					// 当前电池的温度
					int temperature = intent.getIntExtra(
							BatteryManager.EXTRA_TEMPERATURE, -1);

				} else if (action.equalsIgnoreCase(Intent.ACTION_BATTERY_LOW)) {
					// 表示当前电池电量低
					// System.out.println("BatteryChangedReceiver ACTION_BATTERY_LOW---");
				} else if (action.equalsIgnoreCase(Intent.ACTION_BATTERY_OKAY)) {
					// 表示当前电池已经从电量低恢复为正常
					// System.out.println("BatteryChangedReceiver ACTION_BATTERY_OKAY---");
				}

				// 保存电量和状态
				powerlevel = level;
				powerstate = status;
			}
		};
		batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
		registerReceiver(batteryLevelRcvr, batteryLevelFilter);
	}

	// java调用cocos2d-x的地方
	// 选择图片扫描返回，返回值为生成的图片名字，需要一段时间写入才能读取
	public static native void BatteryReturn(final int level);

	public static native void closeLoadLayer();

	// public static native void share2weixinBack(final int level);
	public static native void share2weixinBack(final int level);

	public static native void WeiXinLogin(final String code, final String appid);

	public static native void gameComesToForeground();

	// ======================================获取wifi信号强度===========================================
	private WifiManager wifiManager = null; // Wifi管理器
	private static boolean bHaveMonitorWifi = false; // 是否开启wifi监听

	public static void ToMonitorWifi() {
		if (bHaveMonitorWifi)
			return;
		bHaveMonitorWifi = true;
		nAppActivity.monitorWifiState();
	}

	private void monitorWifiState() {
		// 获得Wifi管理器
		wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);

		if (wifiManager != null) {
			// 使用定时器,每隔5秒获得一次信号强度值
			Timer timer = new Timer();

			TimerTask task = new TimerTask() {
				@Override
				public void run() {
					WifiInfo wifiInfo = wifiManager.getConnectionInfo();
					// 获得信号强度值
					// int level = wifiInfo.getRssi();
					int nWSig = WifiManager.calculateSignalLevel(
							wifiInfo.getRssi(), 100);
					// //根据获得的信号强度发送信息
					// int lv = 5;
					// if (level <= 0 && level >= -50) {
					// lv = 1;
					// } else if (level < -50 && level >= -70) {
					// lv = 2;
					// } else if (level < -70 && level >= -80) {
					// lv = 3;
					// } else if (level < -80 && level >= -100) {
					// lv = 4;
					// } else {
					// lv = 5;
					// }
					// Log.e("NekoTest", "new SSID : " + wifiInfo.getSSID() +
					// "   signal strength : "+wifiInfo.getRssi() + "   强度:" +
					// nWSig);
					// Log.e("NekoTest", "Wifi强度是"+level+" 等级"+lv);
					WifiStateReturn(nWSig);

				}
			};

			timer.schedule(task, 1000, 5000);
		}
	}

	public static native void WifiStateReturn(final int level);

	public static native void setSDKType(final int level);

	public void openAndroidView(final String url) {
		this.runOnUiThread(new Runnable() {// 在主线程里添加别的控件
			public void run() {
				if (m_webView != null) {
					removeWebView();
				}
				// 初始化webView
				m_webView = new WebView(nAppActivity);
				// 设置webView能够执行javascript脚本
				m_webView.getSettings().setJavaScriptEnabled(true);
				m_webView.getSettings().setAllowFileAccess(true);
				m_webView.getSettings().setLoadsImagesAutomatically(true);
				// 设置可以支持缩放
				m_webView.getSettings().setSupportZoom(true);// 设置出现缩放工具
				m_webView.getSettings().setBuiltInZoomControls(true);
				// 载入URL
				m_webView.loadUrl(url);

				// m_webView.loadUrl("file:///android_asset/Test.html");
				// 使页面获得焦点
				m_webView.requestFocus();
				// 如果页面中链接，如果希望点击链接继续在当前browser中响应
				m_webView.setWebViewClient(new WebViewClient() {
					public boolean shouldOverrideUrlLoading(WebView view,
							String url) {
						URI uri = URI.create(url);
						Log.d("weburl", "uri.getScheme()=" + uri.getScheme());
						Log.d("weburl", "urlString=" + url);
						if (uri != null && uri.getScheme().equals("close")) {
							removeWebView();
							return true;
						}
						/*
						 * if (url.indexOf("tel:") < 0) { view.loadUrl(url); }
						 */

						try {
							if (url.startsWith("weixin://") // 微信
									|| url.startsWith("alipays://") // 支付宝
									|| url.startsWith("mailto://") // 邮件
									|| url.startsWith("tel://")// 电话
									|| url.startsWith("dianping://")// 大众点评
									|| url.startsWith("upwrp://")// 汇付宝银联
							// 其他自定义的scheme
							) {
								Intent intent = new Intent(Intent.ACTION_VIEW,
										Uri.parse(url));
								startActivity(intent);
								return true;
							}
						} catch (Exception e) { // 防止crash
												// (如果手机上没有安装处理某个scheme开头的url的APP,
												// 会导致crash)
							return false;// 没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
						}

						view.loadUrl(url);
						return true;
					}

					@Override
					public void onPageFinished(WebView view, String url) {
						// TODO Auto-generated method stub
						super.onPageFinished(view, url);
						Log.d("weburl", "onPageFinished");
					}

				});
				/*
				 * 背景图 m_imageView = new ImageView(nAppActivity);
				 * m_imageView.setImageResource(R.drawable.lobbybg);
				 * m_imageView.setScaleType(ImageView.ScaleType.FIT_XY);
				 */
				/* 初始化线性布局 里面加按钮和webView */
				topLayout = new LinearLayout(nAppActivity);
				topLayout.setOrientation(LinearLayout.VERTICAL);

				/* 初始化返回按钮 */

				// 把image加到主布局里
				// m_webLayout.addView(m_imageView);
				// 把webView加入到线性布局
				// topLayout.addView(backButton);
				// topLayout.addView(m_webView);
				// 再把线性布局加入到主布局

				m_webLayout.addView(m_webView);

				m_webLayout.addView(topLayout);

				Button exitBtn = new Button(getApplicationContext());
				exitBtn.setBackgroundResource(R.drawable.close_btn_web); // 设置图片
				exitBtn.setOnClickListener(new Button.OnClickListener() {

					@Override
					public void onClick(View arg0) {
						removeWebView();
					}
				});

				RelativeLayout.LayoutParams btParams = new RelativeLayout.LayoutParams(
						64, 64); // 设置按钮的宽度和高度
				// btParams.leftMargin = m_webLayout.getWidth() - 34; //横坐标定位
				// btParams.topMargin = 2; //纵坐标定位
				btParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,
						RelativeLayout.TRUE);
				// btParams.
				topLayout.addView(exitBtn, btParams);

				WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
				int winWidth = wm.getDefaultDisplay().getWidth();
				int winHeight = wm.getDefaultDisplay().getHeight();
				exitBtn.setX(winWidth - 100);
				exitBtn.setY(20);
			}
		});
	}

	// 移除webView 把刚才加的所有控件都删掉
	public void removeWebView() {
		// m_webLayout.removeView(m_imageView);
		// m_imageView.destroyDrawingCache();

		// m_webLayout.removeView(topLayout);
		// topLayout.destroyDrawingCache();

		m_webLayout.removeView(m_webView);
		m_webLayout.removeView(topLayout);
		m_webView.destroy();
		m_webView = null;

	}

	public static void AdcallPhone(String phonestr) {
		Log.d("sdk", "tel:" + phonestr);
		Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
				+ phonestr));
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		AppActivity.nAppActivity.startActivity(intent);
	}

	public static void AdClickCopy(final String Textstr) {

		AppActivity.nAppActivity.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				Log.d("sdk", "tel:" + Textstr);
				ClipboardManager cm = (ClipboardManager) AppActivity.nAppActivity
						.getSystemService(Context.CLIPBOARD_SERVICE);
				// 创建普通字符型ClipData
				ClipData mClipData = ClipData.newPlainText("Label", Textstr);
				// 将ClipData内容放到系统剪贴板里。
				cm.setPrimaryClip(mClipData);
				Toast.makeText(AppActivity.nAppActivity, "已复制到剪贴板",
						Toast.LENGTH_LONG).show();
			}
		});
		// 从API11开始android推荐使用android.content.ClipboardManager
		// 为了兼容低版本我们这里使用旧版的android.text.ClipboardManager，虽然提示deprecated，但不影响使用。

	}
	
	public static void setWXParams(String appid, String appsecret) {
		Log.d("setWXParams", "app, " + appid);
		Constants.APP_ID = appid;
	}
	
	public static void addWXReserveID(String appid){
		Log.d("addWXReserveID", "app, " + appid);
		Constants.app_reserve_id_list.add(appid);
	}
	
	private static int curWXIDIndex = 0;
	public static void switchWxToLogin()
	{
		if(curWXIDIndex < Constants.app_reserve_id_list.size()){
			Constants.APP_ID = Constants.app_reserve_id_list.get(curWXIDIndex);
			curWXIDIndex++;
			WeiXinLogin();
		}
	}


	public static void saveInviteImageToCamera(String abfileName, String newName) {
		// 首先保存图片
		String storePath = Environment.getExternalStorageDirectory()
				.getAbsolutePath() + File.separator + "InviteScreen";
		File appDir = new File(storePath);
		if (!appDir.exists()) {
			appDir.mkdir();
		}

		// 创建file对象
		String localFileName = newName;
		File f = new File(storePath, localFileName);
		try {
			f.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		FileInputStream fi = null;
		FileOutputStream fo = null;
		FileChannel in = null;
		FileChannel out = null;
		try {
			fi = new FileInputStream(abfileName);
			fo = new FileOutputStream(f);
			in = fi.getChannel();// 得到对应的文件通道
			out = fo.getChannel();// 得到对应的文件通道
			in.transferTo(0, in.size(), out);// 连接两个通道，并且从in通道读取，然后写入out通道
			fo.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fi.close();
				in.close();
				fo.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// 其次把文件插入到系统图库
		// try {
		// MediaStore.Images.Media.insertImage(AppActivity.nAppActivity.getContentResolver(),
		// f.getAbsolutePath(), localFileName, null);
		// } catch (FileNotFoundException e) {
		// e.printStackTrace();
		// }

		// 最后通知图库更新
		Uri uri = Uri.fromFile(f);
		AppActivity.nAppActivity.sendBroadcast(new Intent(
				Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
		// ToShowToast("保存成功，请在相册中查看！");
	}

	public boolean onKeyDown(int keyCoder, KeyEvent event)// 重载函数，android手机实体返回键回调函数
	{
		if (m_webView != null) {
			if (m_webView.canGoBack() && keyCoder == KeyEvent.KEYCODE_BACK) {// 如果网页能回退则后退，如果不能后退移除WebView
				m_webView.goBack();
			} else {
				removeWebView();
			}
		}

		return false;
	}

	/**
	 * 获取META-INFO下面的渠道
	 * 
	 * @param context
	 * @return
	 */
	public static String _channel;

	public static String getChannel(Context context) {
		if (!TextUtils.isEmpty(_channel)) {
			return _channel;
		}
		ApplicationInfo appinfo = context.getApplicationInfo();
		String sourceDir = appinfo.sourceDir;
		ZipFile zipfile = null;
		final String start_flag = "META-INF/channel_";
		try {
			zipfile = new ZipFile(sourceDir);
			Enumeration<?> entries = zipfile.entries();
			while (entries.hasMoreElements()) {
				ZipEntry entry = ((ZipEntry) entries.nextElement());
				String entryName = entry.getName();
				if (entryName.contains(start_flag)) {
					_channel = entryName.replaceAll(start_flag, "");
					return _channel;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (zipfile != null) {
				try {
					zipfile.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "";
	}

	public byte[] getBytesOfImage() {
		Bitmap bmp;
		bmp = BitmapFactory.decodeResource(AppActivity.this.getResources(),
				R.drawable.icon);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
		byte[] byteArray = baos.toByteArray();
		bmp.recycle();
		return byteArray;
	}

	// 压缩
	public static byte[] bmpToByteArray(final Bitmap bmp,
			final boolean needRecycle) {
		Log.i("bmpToByteArray", "正在运行中");

		int i = bmp.getWidth();
		int j = bmp.getHeight();
		Log.i("--------------", "i==" + i + "----------j===" + j);
		Bitmap localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565);
		Canvas localCanvas = new Canvas(localBitmap);

		while (true) {
			localCanvas.drawBitmap(bmp, new Rect(0, 0, i, j), new Rect(0, 0, i,
					j), null);
			if (needRecycle) {
				bmp.recycle();
				System.gc();
			}
			ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
			localBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
					localByteArrayOutputStream);
			localBitmap.recycle();
			System.gc();
			byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
			try {
				localByteArrayOutputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return arrayOfByte;
		}
	}

	// 以下皆为爱我项目所有功能
	static public void savepath(final String path) {
		Editor sharedata = sharedPreferences.edit();
		sharedata.putString("path", path);
		sharedata.commit();
		Log.i("iwproduct..............path.........save.........by.........c++",
				path);
	}

	// 官包类型
	public static String GetOfficialType() {
		String str = new String();
		{
			try {
				ApplicationInfo ai = nAppActivity.getPackageManager()
						.getApplicationInfo(nAppActivity.getPackageName(),
								PackageManager.GET_META_DATA);
				Bundle bundle = ai.metaData;
				Object obj = bundle.get("OFFICIAL_TYPE");
				str = obj.toString();

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return str;
	}

}
